<template>
	<view class="main">
		<u-navbar :title="list[type] + '编辑'"></u-navbar>
		<view class="see">
			<view class="user">
				<u-avatar :src="user.avatar"></u-avatar>
				<view class="username">{{ user.nickName }}</view>
			</view>
			<view class="edit">
				<u-input
					v-model="value"
					type="textarea"
					placeholder="这一刻的想法..."
					:border="border"
					:height="height"
					:auto-height="autoHeight"
					:clearable="clearable"
					class="text"
					:maxlength="-1"
				/>

				<view v-if="type == 1">
					<view class="theme">
						携带本周主题：{{ theme }}
						<u-checkbox-group>
							<u-checkbox v-model="item.checked" v-for="(item, index) in radioList" :key="index" :name="item.name">
								{{ item.name }}
							</u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="uploadimg">
						<u-upload
							:action="action"
							:auto-upload="false"
							ref="uUpload"
							max-count="1"
							:header="header"
							:show-progress="showProgress"
							@on-uploaded="submit"
						></u-upload>
					</view>
				</view>
			</view>

			<u-button @click="upload" size="default" class="btn">发表</u-button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			user: {},
			list: ['问大家', '加油站', '撕逼墙'],
			type: 0,
			value: '',
			border: false,
			height: 200,
			autoHeight: true,
			clearable: false,
			showProgress: false,
			action: 'http://b.ido.hpjpw.com/prod-api/ido/file/upload',
			fileList: [
				{
					url: ''
				}
			],
			header: {},
			theme: '',
			themeId:-1,
			radioList: [
				{
					name: '',
					checked: true,
					disabled: false
				}
			],
			radio: '',
			imgKey: ''
		};
	},
	async onLoad(option) {
		console.log('op', option);
		this.type = option.index; // 判断是发布问大家（0）加油站（1）还是撕逼墙的消息（2）
		// 简单的进行了一下简易深拷贝，因为uniapp自己的问题，会直接能修改vuex里面存取的数据
		this.user = JSON.parse(JSON.stringify(this.$store.getters.getStorageUser));
		console.log('user', this.user);
		if (this.type == 2) {
			this.user.avatar = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1305454818,873736954&fm=26&gp=0.jpg';
			this.user.nickName = '匿名';
		}
		// 这里是为了上传图片的时候能够够携带一个token
		let token = this.$store.state.token || uni.getStorageSync('token');
		this.header.Authorization = token;
		
		let topic = await this.$u.api.getTopic()
		console.log('topic ',topic)
		if(topic.data.topicContent){
			this.theme = topic.data.topicContent
			this.themeId = topic.data.topicId
		}
	},

	methods: {
		async upload() {
			console.log('上传图片');

			uni.showLoading({
				title: '发送中'
			});
			if (this.$refs.uUpload && this.$refs.uUpload.lists.length>0) {
				let lists = this.$refs.uUpload.lists;
				console.log('cscs',lists)
				let res1 = await this.$u.api.qiniuToken(lists);
				console.log('res1', res1);
				let { key, token } = res1;
				this.imgKey = '/'+key;
				let fileUrl = lists[0].url;
				this.$u.api.qiniuUpload({ key, token, fileUrl }, param => {
					console.log('七牛云上传成功,param:', param);
					return param;
				});
				console.log('imgkey',this.imgKey)
				this.submit(lists);
			} else {
				this.submit();
			}
		},
		async submit(lists, name) {
			// let fileList = this.$refs.uUpload.lists || [];
			console.log('file list', lists);
			lists = lists || [];
			if (lists.length > 0) {
				// 可以在此上传到服务端
				lists = lists[0];
				let token = this.$store.state.token || uni.getStorageSync('token');
				if (this.type == 1) {
					let param = {
						reportId: this.user.userId,
						content: this.value,
						picture1: this.imgKey,
						topicId: this.themeId
					};
					this.$u.api
						.addCheerMoment(param)
						.then(res => {
							console.log('img cheer res', res);
							this.showToastSuccess(param);
						})
						.catch(err => {
							this.showToastFail();
						});
				} else {
					// 问大家板块的动态发布
				}
			} else {
				console.log('没有图片需发送 type:', this.type);

				switch (this.type) {
					case '0': // 问大家发布
						break;
					case '1': // 加油站发布
						let cheerparam = {
							reportId: this.user.userId,
							content: this.value,
							topicId: this.themeId
						};
						this.$u.api
							.addCheerMoment(cheerparam)
							.then(res => {
								console.log('cheer res', res);
								this.showToastSuccess(cheerparam);
							})
							.catch(err => {
								this.showToastFail();
							});
						break;
					case '2': // 撕逼墙发布
						// console.log('撕逼墙发布');
						let anonymousparam = {
							reportId: this.user.userId,
							content: this.value
						};
						this.$u.api
							.addAnonymousMoment(anonymousparam)
							.then(res => {
								console.log('anonymous res', res);
								this.showToastSuccess(anonymousparam);
							})
							.catch(err => {
								this.showToastFail();
							});
						break;
					default:
						this.showToastFail();
				}
			}

			return;
		},
		finishJumpTab() {
			uni.switchTab({
				url: '../../internship/internship'
			});
		},
		showToastSuccess(param) {
			uni.hideLoading();
			param.type = this.type;
			param.picture1 = this.$store.state.projectIp + param.picture1;
			let finishJumpTab = this.finishJumpTab;
			let emitPublish = this.emitPublish;

			uni.showToast({
				title: '发送成功',
				duration: 1000,
				icon: 'none',
				success() {
					// 这两个的顺序需要特别注意,因为是在onshow的时候监听的
					finishJumpTab();
					emitPublish(param);
				}
			});
		},
		showToastFail() {
			// uni.hideLoading();
			uni.showToast({
				title: '发送失败',
				duration: 1000,
				icon: 'none'
			});
		},
		emitPublish(payload) {
			uni.$emit('publish', payload.type);
		}
	}
};
</script>

<style lang="scss" scoped="scoped">
.main {
	background-color: #f4f5f6;
	height: 100vh;

	.see {
		background-color: #fff;
		padding: 20rpx 0;

		.user {
			margin: 20rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.username {
				margin-left: 20rpx;
				color: #6699ff;
			}
		}

		.edit {
			margin: 0 20rpx;

			.theme {
				margin: 20rpx 0;
				display: flex;
				justify-content: space-between;
			}

			.text {
			}

			.uploadimg {
				margin-left: -5rpx;
			}
		}

		.btn {
			margin: 40rpx 20rpx;
		}
	}
}
</style>
